﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebShopData;

namespace GalaxySale2014
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Article> articles = ArticleDB.GetAllArticles();
                GridViewArticles.DataSource = articles;
                GridViewArticles.DataBind();
                foreach (GridViewRow row in GridViewArticles.Rows)
                {
                    ((TextBox)row.FindControl("TextBoxQ")).Text = "1";
                }
            }
        }

        protected void GridViewArticles_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "AddToCart")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = GridViewArticles.Rows[index];
                var quantity = GetQuantity(row);
                if (quantity > 0)
                {
                    Order currentOrder = Session["CurrentOrder"] as Order;
                    Article article = ArticleDB.GetArticleById(int.Parse(row.Cells[1].Text));
                    OrderRow orderRow = new OrderRow(0, quantity, article);
                    currentOrder.AddOrderRow(orderRow);
                    Session["AddToCartText"] = string.Format("{0}x {1} added!", orderRow.Quantity, orderRow.Article.ArticleName);
                    Response.Redirect("~/Default.aspx");
                }
            }
        }

        private static int GetQuantity(GridViewRow row)
        {
            TextBox textBoxQuantity = (TextBox)row.FindControl("TextBoxQ");
            int quantity = 0;
            int.TryParse(textBoxQuantity.Text.Trim(), out quantity);
            textBoxQuantity.Text = "1";
            return quantity;
        }
    }
}